package me.caofeng.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import me.caofeng.annotation.Authentication;
import me.caofeng.enums.OrderStatus;
import me.caofeng.pojo.AlipayInfo;
import me.caofeng.pojo.Response;
import me.caofeng.pojo.User;
import me.caofeng.service.api.IAlipayService;
import me.caofeng.service.api.IPreparePayService;
import me.caofeng.util.Constant;
import me.caofeng.util.DateUtil;
import me.caofeng.util.JsonUtil;
import me.caofeng.util.PriceUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Copyright © 2017曹峰. All rights reserved.
 *
 * @Prject: mall
 * @Package: me.caofeng.controller
 * @Description:
 * @Author: 曹峰 blog.caofeng.me
 * @Date: 2017-06-28 15:37
 * @Version: V1.0
 */

@Controller
@RequestMapping(value = "pay")
public class PayController {
    private static Logger LOGGER = LogManager.getLogger(PayController.class);

    @Autowired
    private IPreparePayService preparePayService;

    @Autowired
    private IAlipayService alipayService;

    @RequestMapping(value = "callback/alipay", method = RequestMethod.POST)
    @ResponseBody
    public Object alipayCallBack(HttpServletRequest request) {
        LOGGER.info("支付宝回调");
        //获取回调参数
        Map<String, String> map = new HashMap<>();
        request.getParameterMap().forEach((key, value) -> map.put(key, value[0]));
        LOGGER.info(map.get("gmt_payment"));
        return  alipayService.verifyCallback(map);

    }

    @RequestMapping(value = "/alipay/{id}", method = RequestMethod.POST)
    @ResponseBody
    @Authentication
    public Response<String> alipay(@PathVariable("id") String id, HttpSession session) {
        LOGGER.info("发起支付宝支付");
        User user = (User) session.getAttribute(Constant.USER);
        return preparePayService.preparePay(id, user.getUid(), Constant.ALIPAY);
    }

    @RequestMapping(value = "alipay/{id}", method = RequestMethod.GET)
    @ResponseBody
    @Authentication
    public Response payInfo(@PathVariable("id") String orderId, HttpSession session) {
        User user = (User) session.getAttribute(Constant.USER);
        return preparePayService.getPayStatus(orderId, user.getUid(), 1);
    }



}
